﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

/* 第三方网站接口 */
namespace Owen.ThirdSiteAPI.MicroBo
{
    /// <summary>
    /// 请求的方式
    /// </summary>
    public enum MethodType
    {
        GET=1,
        POST=2
    }

    /// <summary>
    /// 用于基本的HTTP访问等
    /// </summary>
    public class HttpRequestHelper
    {
        #region 属性集 受保护的

        private HttpWebRequest request;// = System.Net.WebRequest.Create(outUrl) as HttpWebRequest;
        /// <summary>
        /// 本次请求的请求实例 延迟 暂不开放
        /// </summary>
        protected HttpWebRequest Request
        {
            get { return request; }
            set { request = value; }
        }

        private string url;
        /// <summary>
        /// 请求的地址 暂不开放
        /// </summary>
        protected string Url
        {
            get { return url; }
            set { url = value; }
        }

        /*
         * Expect100Continue
         * 
         * 当该属性设置为 true 时，使用 POST 方法的客户端请求应该从服务器收到 100-Continue 响应，以指示客户端应该发送要发送的数据。
         * 此机制使客户端能够在服务器根据请求报头打算拒绝请求时，避免在网络上发送大量的数据。
         * 
         * 例如，假定 Expect100Continue 属性为 false。当请求发送到服务器时，它包括数据。
         * 如果在读取了请求标头后，服务器要求身份验证并且必须发送 401 响应，则客户端必须用正确的身份验证标头重新发送数据。
         * 
         * 如果该属性为 true，请求报头将发送到服务器。
         * 如果服务器没有拒绝请求，它将发送 100-Continue 响应，指示可以传输数据。
         * 如果像前一个示例那样，服务器要求身份验证，它将发送 401 响应，而客户端不一定未传输数据。
         * 
         * 更改此属性的值并不影响现有 ServicePoint 对象。只影响在更改后创建的新 ServicePoint 对象。
         * 
         */

        private bool expect100Continue = false;
        /// <summary>
        /// 是否先握手 暂不开放
        /// </summary>
        protected bool Expect100Continue
        {
            get { return expect100Continue; }
            set { expect100Continue = value; }
        }

        private string contentType;
        /// <summary>
        /// 内容类型 暂不开放
        /// </summary>
        protected string ContentType
        {
            get { return contentType; }
            set { contentType = value; }
        }

        private MethodType method;
        /// <summary>
        /// 请求方式 GET | POST
        /// </summary>
        protected MethodType Method
        {
            get { return method; }
            set { method = value; }
        }

        #endregion

        #region 构造方法

        /// <summary>
        /// 构造函数 在构造该类的时候 初始化引用类型的属性
        /// </summary>
        protected HttpRequestHelper()
        {
        }

        /// <summary>
        /// 构造函数 在构造该类的时候 初始化引用类型的属性
        /// </summary>
        /// <param name="requestUri">请求的URL资源</param>
        protected HttpRequestHelper(string requestUri)
        {
            this.url = requestUri;
            this.request = WebRequest.Create(this.url);
            this.request.Method = this.method.ToString();
            this.request.ServicePoint.Expect100Continue = this.expect100Continue;
        }

        /// <summary>
        /// 构造函数 在构造该类的时候 初始化引用类型的属性
        /// </summary>
        /// <param name="requestUri">请求的URL资源</param>
        /// <param name="clientHost">请求端主机地址 UserHostAddress</param>
        /// <param name="method">请求方法</param>
        public HttpRequestHelper(string requestUri, string clientHost, MethodType method)
        {
            this.url = requestUri;
            this.request = WebRequest.Create(this.url);
            this.request.Method = this.method.ToString();
            this.request.ServicePoint.Expect100Continue = this.expect100Continue;
            this.request.Headers.Add("API-RemoteIP", clientHost);
        }

        #endregion

        #region 辅助操作方法

        /// <summary>
        /// 为当前请求 加一个头标记
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        protected void AddHeader(string key, string value)
        {
            if (this.request == null)
            {
                return;
            }

            this.request.Headers.Add(key, value);
        }

        #endregion

        #region 请求方法

        /// <summary>
        /// 将数据 写入到请求的流中
        /// POST数据
        /// </summary>
        /// <param name="data"></param>
        protected void WriteRequest(string data)
        {
            using (Stream tmpStream = this.request.GetRequestStream())
            {
                using (StreamWriter tmpWriter = new StreamWriter(tmpStream))
                {
                    tmpWriter.Write(data);
                }
            }
        }

        /// <summary>
        /// 取一个请求的返回信息
        /// </summary>
        /// <returns></returns>
        protected string GetResponse()
        {
            string responseData = string.Empty;

            using (Stream tmpStream = this.request.GetResponse().GetResponseStream())
            {
                using (StreamReader tmpReader = new StreamReader(tmpStream))
                {
                    responseData = tmpReader.ReadToEnd();
                }
            }

            return responseData;
        }

        /// <summary>
        /// GET方式 发起请求
        /// </summary>
        /// <returns></returns>
        public string Get()
        {
            if (this.method == MethodType.POST)
            {
                return null;
            }

            string result = GetResponse();
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Post(string data)
        {
            if (this.method == MethodType.GET)
            {
                return;
            }

            this.request.ContentType = "application/x-www-form-urlencoded";

            WriteRequest(data);

            string result = GetResponse();
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public string PostPicture(string data, string imgPath)
        {
            return null;
        }

        /// <summary>
        /// 请求一个URL地址
        /// </summary>
        /// <param name="url">待请求的地址</param>
        /// <param name="method">请求方式 GET、POST等</param>
        /// <param name="data">待发送的数据</param>
        /// <returns></returns>
        protected static string Request111(string url, string method,string data)
        {
            // 
            HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
            webRequest.Method = method;
            webRequest.ServicePoint.Expect100Continue = false;

            // ???
            //httpWebRequest.Headers.Add("API-RemoteIP", UserRemoteIP);

            StreamReader responseReader = null;
            string responseData;
            try
            {
                Stream tmpS = webRequest.GetRequestStream();
                responseReader = new StreamReader(tmpS);
                responseData = responseReader.ReadToEnd();
            }
            catch (Exception e)
            {
                responseData = e.Message;
            }
            finally
            {
                if (responseReader != null)
                {
                    responseReader.Close();
                }
            }

            return responseData;
        }

        #endregion
    }
}
